package com.meshnetics.gb.type.impl.custom;

import com.meshnetics.gb.type.DataType;

/**
 * Type for list of values. The values of selected type can be holded in list only.
 *
 * @author AKovylin
 */
public abstract class ListDataType extends CustomDataType {
    protected final DataType elementType;

    protected ListDataType(String name, DataType elementType) {
        this(new String[]{name}, elementType);
    }

    protected ListDataType(String[] aliases, DataType elementType) {
        super(aliases);
        if (elementType == null) {
            throw new NullPointerException("elementType is null");
        }
        this.elementType = elementType;
    }

    protected ListDataType(String name, boolean register, DataType elementType) {
        super(name, register);
        if (elementType == null) {
            throw new NullPointerException("elementType is null");
        }
        this.elementType = elementType;
    }

    public DataType getElementType() {
        return elementType;
    }

    protected String formatShortLogString(CustomDataValue value) {
        if (!(value instanceof ListDataValue)) {
            throw new IllegalArgumentException("not a list");
        }
        ListDataValue list = (ListDataValue) value;
        StringBuffer sb = new StringBuffer();
        sb.append(value.getType().getName()).append('(');
        sb.append("elemType=").append(((ListDataType) list.getType()).elementType.getName()).append(',');
        sb.append("length=").append(list.getListSize()).append(',');
        sb.append('[');
        for (int i = 0; i < list.getListSize(); i++) {
            if (i > 0) {
                sb.append(',');
            }
            sb.append(list.getElement(i).getType().getMandatoryFormatter().formatShortLogString(list.getElement(i)));
        }
        sb.append(']').append(')');
        return sb.toString();
    }

    protected String formatMaxLogString(CustomDataValue value) {
        if (!(value instanceof ListDataValue)) {
            throw new IllegalArgumentException("not a list");
        }
        ListDataValue list = (ListDataValue) value;
        StringBuffer sb = new StringBuffer();
        sb.append(value.getType().getName()).append('(').append(value.getType().getClass().getName()).append(',');
        sb.append("elemType=").append(((ListDataType) list.getType()).elementType.getName()).append(',');
        sb.append("length=").append(list.getListSize()).append(',');
        sb.append('[');
        for (int i = 0; i < list.getListSize(); i++) {
            if (i > 0) {
                sb.append(',');
            }
            sb.append(list.getElement(i).getType().getMandatoryFormatter().formatMaxLogString(list.getElement(i)));
        }
        sb.append(']').append(')');
        return sb.toString();
    }
}
